<?php
    // +----------------------------------------------------------------------
    // | 用户管理
    // +----------------------------------------------------------------------
    // | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
    // +----------------------------------------------------------------------
    // | Author: 微尘 <yicmf@qq.com>
    // +----------------------------------------------------------------------
    namespace app\controller\ucenter;

    use think\facade\Config;
    use think\facade\Session;

    class User extends Common
    {
        /**
         * 更新在线时长
         * @return \think\response\Json
         * @throws \Exception
         * @author  : 微尘 <yicmf@qq.com>
         * @datetime: 2019/3/10 19:21
         */
        public function online()
        {
            if (!Session::has('last_active_time') || Session::get('last_active_time') !== time()) {
                Session::set('last_active_time', time());
                // 控制在线时长
                $online = $this->user->onlines()->whereTime('end_time', '>', '-2 minutes')->order('id DESC')->where('ip', $this->request->ip())->find();
                if ($online) {
                    $this->user['online_time'] = $this->user['online_time'] + time() - strtotime($online['end_time']);
                    $this->user['last_active_time'] = time_format();
                    $this->user->save();
                    $online['duration'] = $online['duration'] + time() - strtotime($online['end_time']);
                    $online['end_time'] = $this->user['last_active_time'];
                } else {
                    // 新增记录
                    $online = [];
                    $online['duration'] = 1;
                    $online['start_time'] = time_format();
                    $online['end_time'] = time_format(time() + 1);
                    $this->user->onlines()->save($online);
                    $this->user['online_time'] = $this->user['online_time'] + 1;
                    $this->user['last_active_time'] = $online['end_time'];
                }
                $this->user->isAutoWriteTimestamp(false)->save();
                $data['data']['online_time'] = $this->user['online_time'];

            }else{
				$data['data']['online_time'] = $this->user['online_time'];
			}
            $data['data']['message'] = $this->user->messages()->where('is_read', 0)->where('status', 1)->count('*');;
//            $data['data']['chat'] = $this->user->chats()->where('is_read', 0)->where('status', 1)->count('*');
            $data['code'] = 0;
            return json($data);
        }

    }
